library(effects)
library(tidyverse)
library(stargazer)
library(gridExtra)
library(dplyr)

setwd("~/Dropbox/projects/inseparability/replication")
study1 <- read_csv("study1.csv")

cbPalette <- c("#E69F00", "#0072B2")

study1 <- study1[study1$gc == 1 & study1$Q5 < 3,]

#recode leaners
study1$Q9[study1$Q10 == 1] <- 1
study1$Q9[study1$Q10 == 2] <- 2

#recode reference levels
study1$treatment[study1$treatment == "negative"] <- "Negative Result"
study1$treatment[study1$treatment == "positive"] <- "Positive Result"
study1$treatment <- as.factor(study1$treatment)

study1$pid <- study1$Q9

#filter out pure idependents
study1 <- study1[study1$pid <= 2,]

study1$pid<-recode(study1$pid, "1" = "Democrat", "2" = "Republican")
study1$pid <- as.factor(study1$pid)

study1$race <- NA
study1$race[study1[,"Q5"] == 1 ] <- "White"
study1$race[study1[,"Q5"] == 2 ] <- "Black"
study1 <- study1[!is.na(study1$race),]

study1$race <- as.factor(study1$race)
study1$affectivepolarization <- NA
study1$inparty <- NA
study1$outparty <- NA

study1$inparty[which(study1$pid=="Democrat")] <- study1$Q200_2[which(study1$pid=="Democrat")]
study1$inparty[which(study1$pid=="Republican")] <- study1$Q63_2[which(study1$pid=="Republican")]

study1$outparty[which(study1$pid=="Republican")] <- study1$Q200_2[which(study1$pid=="Republican")]
study1$outparty[which(study1$pid=="Democrat")] <- study1$Q63_2[which(study1$pid=="Democrat")]

study1$affectivepolarization <- study1$inparty - study1$outparty

study1$racepolarization <- NA

study1$inrace <- NA
study1$outrace <- NA

study1$inrace[which(study1$race=="Black")] <- study1$Q202_2[which(study1$race=="Black")]
study1$inrace[which(study1$race=="White")] <- study1$Q201_2[which(study1$race=="White")]

study1$outrace[which(study1$race=="White")] <- study1$Q202_2[which(study1$race=="White")]
study1$outrace[which(study1$race=="Black")] <- study1$Q201_2[which(study1$race=="Black")]

study1$racepolarization <- study1$inrace - study1$outrace


study1$outincome <- NA
study1$outincome[which(study1$Q6>5)] <- study1$Q526_2[which(study1$Q6>5)]

study1$outincome[which(study1$Q6<=5)] <- study1$Q527_2[which(study1$Q6<=5)]



######################
# Manipulation Check
######################
# recode to handle a skipped number in the qualtrics value recode

study1$Q199[study1$Q199==4] <- 3
study1$Q199[study1$Q199==5] <- 4
t.test(Q199~treatment, data=study1)

######################
# Average Spillover
######################

df <- data.frame(group=character(),
				 mean=double(),
				 lower=double(),
				 upper=double(),
				 stringsAsFactors=FALSE)

baseball <-t.test(Q522_2~treatment, data=study1)
immigrants <- t.test(Q528_2~treatment, data=study1)
tspill_party <- t.test(study1$outparty~study1$treatment)
tspill_income <- t.test(study1$outincome~study1$treatment)
tmain <- t.test(study1$outrace~study1$treatment)

35.0907           -            43.7615
52.47876         -             61.85835 
61.83467          -            64.31961 

format_ttest <- function(df, t, n){
	df[nrow(df)+1,] <- c(n, as.numeric(t$estimate[1] - t$estimate[2]), t$conf.int[1],t$conf.int[2])
	df$mean <- as.numeric(df$mean)
	df$upper <- as.numeric(df$upper)
	df$lower <- as.numeric(df$lower)
	return(df)
	
}

df <- format_ttest (df, baseball, "Baseball fan affect")
df <- format_ttest (df, immigrants, "Immigrant affect")
df <- format_ttest (df, tspill_party, "Parallel updating:\nout-partisan affect")
df <- format_ttest (df, tspill_income, "Parallel updating:\nout-income affect")
df <- format_ttest (df, tmain, "Out-racial affect")
df$group <- as.factor(df$group)
df$group <- factor(df$group,levels(df$group)[c(1,2,4,5,3)])

df

(race_ate <- ggplot(df,aes(y=mean,x=group))+
		geom_point()+
		geom_linerange(aes(ymin=lower,ymax=upper))+
		ylim(-30,2)+
		theme_bw()+
		ylab("Difference in mean feeling toward the \nout-group between negative and positive treatments")+
		xlab("") + 
		ggtitle("A: Study 1 (Racial Treatment)") +
		geom_hline(yintercept=0, linetype="dashed") + 
		geom_vline(xintercept=2.5, linetype="solid") +
		annotate("text", x = 2.25, y = -26, label = "Placebo tests") +
		theme(panel.spacing = unit(1, "lines")) + 
		theme(panel.grid.major = element_line(colour = "white"),panel.grid.minor = element_line(colour = "white"), axis.title.x = element_text(vjust=-0.5)) +
		coord_flip())

ggsave(plot=race_ate,"race_ate.eps", device="eps",width=5, height=3)


######################
# Reinforcement
######################

study1$round3.pid <- as.factor(study1$round3.pid)
affpol <- lm(outparty~treatment*round3.pid+race+pid, data=study1)
racepol <- lm(outrace~treatment*round3.pid+race+pid, data=study1)
incomepol <- lm(outincome~treatment*round3.pid+race+pid, data=study1)
summary(racepol)
summary(affpol)
confint(racepol)
confint(affpol)

stargazer(affpol,racepol, covariate.labels=c("Positive Treatment","Player 1 PID - Repubican", "Participant Race - White", "Participant PID - Republican", "Positive Treatment X Player 1 PID Republican"), dep.var.labels = c("Out Party Affect", "Out Race Affect"), omit.stat = c("f", "ser"), digits=2, ci=T, star.cutoffs = c(0.05, 0.01, 0.001))


######################
# Racial resentment
######################

#handle problems with qualtrics recoding
study1$Q84 <- study1$Q84 -14
study1$Q85 <- 20- study1$Q85
study1$Q83 <- 6- study1$Q83
study1$rr <- (study1$Q81 + study1$Q83 + study1$Q83 + study1$Q84) / 4

study1$rrt <- ntile(study1$rr, 3) 
study1$rrt <- as.factor(study1$rrt)

mean(study1$rr[study1$rrt==1], na.rm=T)
mean(study1$rr[study1$rrt==2], na.rm=T)
mean(study1$rr[study1$rrt==3], na.rm=T)

orrr <- lm(outparty~treatment*rrt, data=study1)

stargazer(orrr, covariate.labels=c("Positive Treatment","Racial Resentment Second Tercile", "Racial Resentment Third Tercile", "Positive Treatment X Racial Resentment Second Tercile", "Positive Treatment X Racial Resentment Third Tercile"), dep.var.labels = c("Out-Party Affect", "Out-Race Affect"), omit.stat = c("f", "ser"), type="latex")

######################
# Diff-in-diff
######################

t.test(study1$racepolarization~study1$treatment)
t.test(study1$affectivepolarization~study1$treatment)
13.622273       -               4.418886 
32.59242        -              30.04479 

######################
# Out-group activation
######################

aligned <- lm(outparty~treatment, data= study1[(study1$race=="Black" & study1$pid == "Democrat") | (study1$race!="Black" & study1$pid == "Republican") ,])

not <- lm(outparty~treatment, data= study1[(study1$race=="Black" & study1$pid == "Republican") | (study1$race!="Black" & study1$pid == "Democrat"),])

confint(aligned)
confint(not)

stargazer(aligned, not, covariate.labels=c("Positive Treatment"), dep.var.labels = c("Out Party Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Aligned Out-Groups", "Unaligned Out-Groups"))

####################
# HET
####################

white <- lm(outparty~treatment,data = study1[study1$race == "White",])
black <- lm(outparty~treatment,data = study1[study1$race != "White",])

democrat <- lm(outparty~treatment, data = study1[study1$pid == "Democrat",])
republican  <- lm(outparty~treatment, data = study1[study1$pid != "Democrat",])

stargazer(white, black, democrat, republican, covariate.labels=c("Positive Treatment"), dep.var.labels = c("Spillover to Out Party Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Whites", "Blacks", "Democrats", "Republicans"), type = "latex")

######################
# Out-group activation
######################

aligned <- lm(outparty~treatment, data= study1[(study1$race=="Black" & study1$pid == "Democrat") | (study1$race!="Black" & study1$pid == "Republican") ,])
not <- lm(outparty~treatment, data= study1[(study1$race=="Black" & study1$pid == "Republican") | (study1$race!="Black" & study1$pid == "Democrat"),])
confint(aligned)
confint(not)

stargazer(aligned, not, covariate.labels=c("Positive Treatment"), dep.var.labels = c("Out Party Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Aligned Out-Groups", "Unaligned Out-Groups"))

study1$aligned <- "not"
study1$aligned[(study1$race=="Black" & study1$pid == "Democrat") | (study1$race!="Black" & study1$pid == "Republican")] <- "yes"


###########
# Mechanism
###########

df <- data.frame(group=character(),
				 mean=double(),
				 lower=double(),
				 upper=double(),
				 stringsAsFactors=FALSE)

op_aligned <-t.test(outparty~treatment, data=study1[study1$aligned == "yes",])
op_unaligned <- t.test(outparty~treatment, data=study1[study1$aligned != "yes",])

df <- format_ttest (df, op_aligned, "Sorted Out-Groups")
df <- format_ttest (df, op_unaligned, "Cross-Cutting Out-Groups")
df$group <- as.factor(df$group)
df$group <- factor(df$group,levels(df$group)[c(2,3,1)])

df

(race_mech <- ggplot(df,aes(y=mean,x=group))+
		geom_point()+
		geom_linerange(aes(ymin=lower,ymax=upper))+
		ylim(-30,1)+
		theme_bw()+
		ylab("(Thermometer points)")+
		xlab("") +
		ggtitle("A: Study 1 (Racial Treatment)") + 
		geom_hline(yintercept=0, linetype="dashed") + 
		theme(panel.spacing = unit(1, "lines")) + 
		theme(panel.grid.major = element_line(colour = "white"),panel.grid.minor = element_line(colour = "white"), axis.title.x = element_text(vjust=-0.5)) +
		coord_flip())

ggsave(plot=race_mech,"race_mech.eps", device="eps",width=5, height=1.2)

####### 
# reported race
#######
study1$same <- "Different"
study1$same[study1$round3.pid == study1$pid] <- "Same"

affpol <- lm(outparty~treatment*same+race, data=study1)
racepol <- lm(outrace~treatment*same+race, data=study1)

stargazer(racepol, affpol,  covariate.labels = c("Positive Treatment","Player 1 and Participant Same Party", "Participant Race - White", "Positive Treatment X Player 1 and Participant Same Party","(intercept)"), omit.stat = c("f", "ser"), ci=F, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Out-Race Affect", "Out-Party Affect"), type = "latex")
